package com.dl.mall.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @author DL
 * @create 2022-03-13 16:24
 */
public class JWTUtils {

    private static final String SIGN = "!qwerwwdl";

    private static final String TEST_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlX25hbWUiOiJzdXBlciIsInVzZXJfaWQiOiIyMzkxOTEwMzQwIiwibmFtZSI6IueuoeeQhuWRmOWogeWogTExIiwic3RhdGUiOiIxIiwiZXhwIjoxNjQ3NzcyODU5LCJ1c2VybmFtZSI6ImFkbWluIn0.sfS1dekY-cWRW_tLIKl51iuiZ7kkzVtJ1kg5cq-E7K4";

    /**
     * 生成token
     * @return token
     */
    public static String getToken(Map<String, ?> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);//默认七天过期
        //instance.add(Calendar.SECOND,20);//默认七天过期
        JWTCreator.Builder builder = JWT.create();//创建jwt

        map.forEach((k,v)->{
            builder.withClaim(k, String.valueOf(v));//payload
        });
        String token = builder.withExpiresAt(instance.getTime())//过期时间
                .sign(Algorithm.HMAC256(SIGN));//签名

        return token;
    }

    /**
     *验证token
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

/*
    *//**
     * 获取token信息
     * @param token
     * @return
     *//*
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT decodedJWT = verify(token);
        decodedJWT.get
    }*/




    public static void renewal(String token){
        DecodedJWT verify = verify(token);
        Date expiresAt = verify.getExpiresAt();
        System.out.println("expiresAt = " + expiresAt);
        long tokenTime = expiresAt.getTime();
        long nowTime = new Date().getTime();

        long time = nowTime - tokenTime;
        System.out.println("time = " + time);
        if (time > 0){
        }else {
        }
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//今天的日期
    }

    @Test
    public void testJ(){
        renewal(TEST_TOKEN);
    }
}
